﻿using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var host = Host.CreateDefaultBuilder(args)
    .ConfigureServices((hostContext, services) =>
    {
        services.AddMemoryCache();
    })
    .Build();

using (var serviceScope = host.Services.CreateScope())
{
    var services = serviceScope.ServiceProvider;
    var cache = services.GetRequiredService<IMemoryCache>();

    var options = new MemoryCacheEntryOptions()
    {
        SlidingExpiration = TimeSpan.FromSeconds(1.5),
    };
    options.RegisterPostEvictionCallback((key, value, reason, state) =>
    {
        Console.WriteLine("key=" + key);
        Console.WriteLine("value=" + value);
        Console.WriteLine("reason=" + reason);
        Console.WriteLine("state=" + state);
    }, "statestr");

    cache.Set("key", "value1", options);
    Console.WriteLine($"{DateTime.Now:HHmmss}_Init_{cache.Get("key")}");
    Thread.Sleep(1000);
    Console.WriteLine($"{DateTime.Now:HHmmss}_First_{cache.Get("key")}");
    Thread.Sleep(2000);
    Console.WriteLine($"{DateTime.Now:HHmmss}_Second_{cache.Get("key")}");
    Thread.Sleep(2000);
    Console.WriteLine($"{DateTime.Now:HHmmss}_Second_{cache.Get("key")}");
    Thread.Sleep(2000);
    Console.WriteLine($"{DateTime.Now:HHmmss}_Second_{cache.Get("key")}");
    Thread.Sleep(2000);
    Console.WriteLine($"{DateTime.Now:HHmmss}_Second_{cache.Get("key")}");
}
